package com.xigege.netty.nettyComponent.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup(2);
        ChannelFuture future = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler( LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress("localhost", 6666));

        Channel channel = future.sync().channel();

        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                if (line .equals("q")){
                    // 异步操作，其他线程执行关闭，本线程接着走
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        }).start();
        // 获取CloseFuture对象，关闭通道后的善后工作
        // 1）.同步处理关闭
//        ChannelFuture channelFuture = channel.closeFuture();
//        System.out.println("waiting close...");
//        channelFuture.sync();
//        System.out.println("通道关闭，开始善后工作...");

        // 2）。异步处理关闭
        ChannelFuture channelFuture = channel.closeFuture();
        System.out.println("waiting close...");
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("通道关闭，开始善后工作...");
                group.shutdownGracefully();
            }
        });
    }
}
